package com.sun.servlet.user;

import com.sun.pojo.User;
import com.sun.service.user.UserService;
import com.sun.service.user.UserServiceImpl;
import com.sun.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Sun
 * @Date 2020/4/25 11:53
 * @Version 1.0
 */
public class LoginServlet extends HttpServlet {

    //servlet：控制层，调用业务层
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取输入的用户名和密码
        String userCode = req.getParameter("userCode");
        String password = req.getParameter("userPassword");

        User user = null;

        //调用业务层，和数据库中的密码进行比对
        UserService userService = new UserServiceImpl();

        try {
            user = userService.login(userCode, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(user!=null && user.getUserPassword().equals(password)){//查有此人且密码正确
            //把用户信息放进session
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //重定向到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else {
            //查无此人，转发到登陆界面，并提示用户名或密码错误
            req.setAttribute("error", "用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
